package com.yusp75.myexam.com.yusp75.myexam.ui.browse

import android.annotation.SuppressLint
import android.content.res.Resources
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.RecyclerView
import com.yusp75.myexam.R
import com.yusp75.myexam.ui.browse.BrowseViewModel
import androidx.core.view.isVisible
import androidx.recyclerview.widget.DiffUtil
import com.yusp75.myexam.data.QuestionWithStats
import com.yusp75.myexam.databinding.ItemQuestionBinding
import androidx.core.view.isGone
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.lifecycleScope
import androidx.paging.PagingDataAdapter
import com.yusp75.myexam.com.yusp75.myexam.data.QuestionFilter
import kotlinx.coroutines.launch

class BrowseAdapter(
    private val viewModel: BrowseViewModel,
    private val lifecycleOwner: LifecycleOwner
) : PagingDataAdapter<QuestionWithStats, RecyclerView.ViewHolder>(COMPARATOR) {

    companion object {
        private const val TYPE_QUESTION = 0
        private const val TYPE_LOADING = 1
        private const val TYPE_ERROR = 2

        private val COMPARATOR = object : DiffUtil.ItemCallback<QuestionWithStats>() {
            override fun areItemsTheSame(oldItem: QuestionWithStats, newItem: QuestionWithStats) =
                oldItem.id == newItem.id

            override fun areContentsTheSame(
                oldItem: QuestionWithStats,
                newItem: QuestionWithStats
            ) =
                oldItem == newItem
        }
    }

    override fun getItemViewType(position: Int) = when (getItem(position)) {
        null -> TYPE_LOADING  // Paging3用null表示加载项
        else -> TYPE_QUESTION
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = when (viewType) {
        TYPE_LOADING -> LoadingViewHolder(
            ItemQuestionBinding.inflate(LayoutInflater.from(parent.context), parent, false)
        )

        else -> QuestionViewHolder(
            ItemQuestionBinding.inflate(LayoutInflater.from(parent.context), parent, false)
        )
    }

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        when (holder) {
            is QuestionViewHolder -> {
                holder.bind(getItem(position)!!)
                holder.clearState()
            }

            is ErrorViewHolder -> {}
        }
    }

    // ViewHolders
    inner class QuestionViewHolder(private val binding: ItemQuestionBinding) :
        RecyclerView.ViewHolder(binding.root) {
        private val tip = ContextCompat.getDrawable(binding.root.context, R.drawable.ic_tip)

        @SuppressLint("SetTextI18n")
        fun bind(item: QuestionWithStats) {
            binding.apply {
                tvContent.text = "${item.id}. ${item.content}"
                tvAnalysis.text = item.analysis
                // tip图标状态
                binding.tvAnswer.apply {
                    text = item.answer
                    // 统一处理图标状态（显示/隐藏）
                    setCompoundDrawablesRelativeWithIntrinsicBounds(
                        null,
                        null,
                        if (item.analysis.isNullOrEmpty()) null else tip,
                        null
                    )
                    // 设置图标与文本间距（8dp）
                    compoundDrawablePadding = 8.dpToPx()
                }
                // 分析不为空，能点击
                tvContent.setOnClickListener {
                    when {
                        item.analysis.isNullOrBlank() -> {
                            // 无内容时不响应点击（可选添加视觉反馈）
                            tvContent.isClickable = false
                            tvContent.isFocusable = false
                        }

                        tvAnalysis.isVisible -> tvAnalysis.visibility = View.GONE
                        else -> tvAnalysis.visibility = View.VISIBLE
                    }.also {
                        // TV设备需保持焦点链完整
                        if (tvAnalysis.isGone) {
                            tvAnalysis.nextFocusUpId = View.NO_ID
                        }
                    }
                }

                // 是否显示收藏和已学会
                lifecycleOwner.lifecycleScope.launch {
                    viewModel.mFilter.collect { filter ->
                        binding.btnFavorite.visibility = when (filter) {
                            QuestionFilter.FAVORITE, QuestionFilter.ALL -> View.VISIBLE
                            else -> View.GONE
                        }
                        binding.btnMastered.visibility = if (filter == QuestionFilter.ONLYWRONG) {
                            View.VISIBLE
                        } else {
                            View.GONE
                        }
                    }
                }

                // 收藏
                binding.btnFavorite.apply {
                    isSelected = item.favorite == true
                    setOnClickListener {
                        isSelected = !isSelected
                        viewModel.updateFavorite(item.id, isSelected)
                    }
                }

                // 移除已会的
                binding.btnMastered.apply {
                    setOnClickListener {
                        viewModel.delRecord(item.id)
                    }
                }

            } // fun bind apply
        } // fun bind

        fun clearState() {
            binding.tvAnalysis.visibility = View.GONE
        }
    }

    class LoadingViewHolder(binding: ItemQuestionBinding) :
        RecyclerView.ViewHolder(binding.root)

    class ErrorViewHolder(
        private val binding: ItemQuestionBinding
    ) :
        RecyclerView.ViewHolder(binding.root) {

        fun bind(message: String) {
            binding.errorText.text = message
            binding.retryButton.setOnClickListener {
                (binding.root.context as? LifecycleOwner)?.lifecycleScope?.launch {
                    // ***
                }
            }
        }
    }

    private fun Int.dpToPx(): Int =
        (this * Resources.getSystem().displayMetrics.density).toInt()

    //
}

